<template>
    <div class="app-container">
        <el-form inline>
            <el-form-item>
                <el-input v-model="searchObj.username" placeholder="请输入内容"></el-input>
            </el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
            <el-button>清空</el-button>
        </el-form>
        <div style="margin-bottom:20px">
            <el-button type="primary" @click="add">添 加</el-button>
            <el-button type="danger" @click="revomveUsers" :disabled="selectedIds.length===0">批量删除</el-button>
        </div>
        <el-dialog
        :title="user.id ? '修改用户' : '添加用户'"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose">
     
        <el-form label-width="100px" :model="user"  ref="user" :rules="rules">
        <el-form-item label="用户名" prop="username" label-width="100px" :rules="[
      { required: true, message: '用户名不能为空'},  
      { min: 4, message: '用户名不能小于4位' },
      
    ]" >
      <el-input  v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" label-width="100px" :rules="[
      { required: true, message: '用户昵称不能为空'},
    ]" >
        <el-input v-model="user.nickName"></el-input>
        </el-form-item>    
        <el-form-item label="用户密码" label-width="100px"  v-if="!user.id" :rules="[
      { required: true, message: '用户密码不能为空'},
      { type: 'number', message: '用户密码必须为数字值'}
    ]">
            <el-input v-model.number="user.password "></el-input>
        </el-form-item>
      </el-form>

    <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addOrUpdate">确 定</el-button>
  </span>
        </el-dialog>
        <el-dialog title="设置角色" :visible.sync="dialogRoleVisible" :before-close="resetRoleData">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled :value="user.username"></el-input>
        </el-form-item>

        <el-form-item label="角色列表">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="userRoleIds" @change="handleCheckedChange">
            <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">{{role.roleName}}</el-checkbox>
          </el-checkbox-group>
          
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button :loading="loading" type="primary" @click="assignRole">保存</el-button>
        <el-button @click="resetRoleData">取消</el-button>
      </div>
    </el-dialog>
        <el-table :data="usermanager"  @selection-change="handleSelectionChange" style="width: 100%"  v-loading="loading"> 
            <el-table-column type="selection" width="55px">
            </el-table-column>
            <el-table-column type="index" label="序号" width="55px">
            </el-table-column>
            <el-table-column label="用户名" prop="username"></el-table-column>
            <el-table-column label="用户昵称" prop="nickName"></el-table-column>
            <el-table-column label="用户列表" prop="roleName"></el-table-column>
            <el-table-column label="创建时间" prop="gmtCreate"></el-table-column>
            <el-table-column label="更新时间" prop="gmtModified"></el-table-column>
            <el-table-column label="操作" width="230">
                <template slot-scope="{row}">
                    <el-button type="info" size="small" icon="el-icon-user-solid" 
                        @click="showAssignRole(row)"  title="分配角色">

                    </el-button>
                    
                    <el-button type="primary" size="small" icon="el-icon-edit"
                       @click="showUpdateUser(row)"  title="修改用户">
                    </el-button>
                    <!-- <el-popconfirm :title="`确定删除 ${row.username} 吗?`" @onConfirm="removeUser(row.id)"> -->
                    <el-button style="margin-left:10px" slot="reference" type="danger" size="small"
                            icon="el-icon-delete" title="删除用户" @click="deleteuseritem(row)">
                    </el-button>
                    <!-- </el-popconfirm> -->
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
      a='pageSize 改变时会触发' 
      @size-change="handleSizeChange"
      b="currentPage 改变时会触发"
      @current-change="handleCurrentChange"
      c="每页显示个数选择器的选项设置"
      :page-sizes="limit"
      d="每页显示条目个数，支持 .sync 修饰符"
      :page-size="limit"
      e="组件布局，子组件名用逗号分隔"
      layout="prev, pager, next, jumper, ->, sizes,total"
      f="总条目数"
      background
      :total="total">
    </el-pagination>
        <!-- <el-pagination
    :current-page="page"
    :total="total"
    :page-size="limit"
    :page-sizes="[5,10,20,30,40,50,100]"
    style="padding:20px 0;"
    layout="prev,pager,next,jumper,->,sizes,total"
    @current-change="getUsers"
    @size-change="handleSizeChange"
    >

    </el-pagination> -->
    </div>
</template>

<script>
import { use } from 'echarts';
import { nextTick } from 'process';

export default {
    data() {

        return {
            // sousuo:'',
            loading:false,
            limit:5,
            total:0,
            page:1,
        //双向绑定的表单数据
            user:{
                username:'',
                nickName:'',
                password:''
            },
        // 用户的角色ID的列表
            userRoleIds: [], 
        //空数组 搜索用的空数组
            users:{
                username: ''
            },
        // 是否全选     
            checkAll: false, 
            //所有角色
            allRoles:[],
            dialogVisible: false,
            
            total: 0,
            limit: 5,
            searchObj: {
                username: ''
            },
            dialogRoleVisible: false, // 是否显示角色Dialog
            usermanager: []
            ,
            selectedIds :[],
            //修改与添加的标志符号
            // flag:1
            //设置角色的储存东西

            // tableData: [{
            //     date: '2016-05-02',
            //     name: '王小虎',
            //     address: '上海市普陀区金沙江路 1518 弄'
            // }, {
            //     date: '2016-05-04',
            //     name: '王小虎',
            //     address: '上海市普陀区金沙江路 1517 弄'
            // }, {
            //     date: '2016-05-01',
            //     name: '王小虎',
            //     address: '上海市普陀区金沙江路 1519 弄'
            // }, {
            //     date: '2016-05-03',
            //     name: '王小虎',
            //     address: '上海市普陀区金沙江路 1516 弄'
            // }],
        }
    },
    created() {
        this.loading=true
        this.getUsers()
        this.loading=false
    },
    methods: {
        //保存并且发送请求分配角色权限
            assignRole(){
                this.$API.user.assignRoles(this.user.id,this.userRoleIds.join(','))
                this.$message.success('分配成功')
                this.getUsers()
                this.dialogRoleVisible=false
            }
            ,
        //搜素按钮
            search(){
                 this.getUsers()
                 this.usermanager = []
                 this.$message.success('搜索成功')
            }
            ,
        //删除用户deleteuseritem
            deleteuseritem(row){
                this.$API.user.removeById(row.id)
                this.getUsers()
                this.$message.success('删除成功')
            }
            ,
        //全选按钮
            handleCheckAllChange(value){
                //垃圾逻辑
            // this.checkAll = !this.checkAll
            // this.userRoleIds = !this.userRoleIds
            //value当前勾选状态true/false 卧槽 早说啊
             // 如果当前全选, userRoleIds就是所有角色id的数组, 否则是空数组
             this.userRoleIds = value ?  this.allRoles.map(item =>item.id) : this.allRoleIds = []
            // 如果当前不是全选也不全不选时, 指定为false
            this.isIndeterminate = false

            },
        //分页重新获取
            handleCurrentChange(val) {
                // console.log(val);
            const result2 =this.getUsers(this.page=val,this.limit)
            console.log(result2)
            },
        //分配角色按钮
            async showAssignRole(row){
            this.dialogRoleVisible = true
            // console.log(row)
            this.user.username=row.username
            this.user.id=row.id
            const result = await this.$API.user.getRoles(this.user.id)
                    this.allRoles=result.data.allRolesList
                    this.userRoleIds=result.data.assignRoles.map(item=>item.id)
                    console.log(this.userRoleIds)
                    // console.log(result)
        }
        ,
        //确定关闭的逻辑
        handleClose(done) {
        this.$confirm('快点关吧，烦死了')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      }
    ,
        // 获取分页列表
        async getUsers(page = 1) {
            this.page = page
            console.log(page)
            console.log(this.limit)
            const result = await this.$API.user.getPageList(page, this.limit, this.searchObj)
            this.usermanager = result.data.items

            console.log(this.usermanager)
            this.total =result.data.total

        
        },
         //普通按钮
        handleCheckedChange (value) {
        const {userRoleIds, allRoles} = this
      //全选状态
        //   this.checkAll = userRoleIds.length === allRoles.length && allRoles.length>0
        this.checkAll = userRoleIds.length === allRoles.length && allRoles.length > 0
        //半选状态
          this.isIndeterminate = userRoleIds.lengtrowh>0 && userRoleIds.length<allRoles.length
        // this.isIndeterminate =allRoleIds.length && allRoleIds.length > 0 && userRoleIds.length <allRoles.length
        },
        
        add(){
            this.dialogVisible = true
            // this.user={
            //     username:'',
            //     nickname:'',
            //     password:''
            // }  
            

        }
        ,
        //列表选择状态改变
        handleSelectionChange(selection){
            this.selectedIds = selection.map(item => item.id)
        }
        ,
        // 修改用户
        showUpdateUser(row){
            // this.user={}  
            // this.users.id=row.id
            this.dialogVisible = true
            // console.log(row)
                this.user.username=row.username
                 this.user.nickName=row.nickName
                 this.user.password=row.password
                 this.user.id=row.id
                // this.user={}
                //  this.dialogVisible = false
                this.$message.success('修改成功')
        } 
        ,   
        // addOrUpdate(){

        // }
        // ,

        addOrUpdate(){
                // this.users.username=this.user.username
                //  this.users.nickName=this.user.nickName
                //  this.users.password=this.user.password
                this.loading=true
                if(this.user.id){
                    this.$API.user.update(this.user)
                }else{
                    this.$API.user.add(this.user) 
                }
                this.loading=false
                this.user={
                username:'',
                nickName:'',
                password:''
                }
                this.dialogVisible = false
                this.$message.success('添加更新成功')
                this.getUsers()
                         
                // nextTick(()=>{
                //    
                // })
             

        }
        ,
    //     showAssignRole(){
    //         this.user.username=row.username
    // }
//         watch: {
//     // 如果 `question` 发生改变，这个函数就会运行
//         user: function (newQuestion, oldQuestion) {
//          this.answer = 'Waiting for you to stop typing...'
//          this.debouncedGetAnswer()
//          this.getUsers(page=1)
//     }
//   },
    },
}
</script>

<style scoped>

</style>